package com.yanwq.sayhi.common.client;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者：yanweiqiang。
 * 日期：2016/6/20 0020。
 */
public class OkRequestParams {
    Map<String, String> getBody;
    FormBody.Builder formBody;
    MultipartBody.Builder multipartBody;

    public OkRequestParams() {
        super();
    }

    public OkRequestParams put(String name, Object value) {
        if (value instanceof File) {
            put(name, ((File) value).getName(), (File) value);
            return this;
        }

        try {
            if (formBody == null) {
                formBody = new FormBody.Builder();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (getBody == null) {
            getBody = new HashMap<>();
        }

        getBody.put(name, String.valueOf(value));
        formBody.add(name, String.valueOf(value));
        return this;
    }

    public OkRequestParams put(String name, String filename, File file) {
        try {
            if (multipartBody == null) {
                multipartBody = new MultipartBody.Builder();
            }
            RequestBody body = RequestBody.create(MediaType.parse(""), file);
            multipartBody.addFormDataPart(name, filename, body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public RequestBody getRequestBody() {
        if (multipartBody != null) {

            if (formBody != null) {
                multipartBody.addPart(formBody.build());
            }

            return multipartBody.build();
        } else {
            return formBody.build();
        }
    }

    public String get() {
        if (getBody == null || getBody.size() == 0) {

            return "";
        }

        StringBuilder builder = new StringBuilder();

        builder.append("?");

        for (String key : getBody.keySet()) {
            builder.append(key).append("=").append(getBody.get(key));
            builder.append("&");
        }

        builder.deleteCharAt(builder.length() - 1);

        return builder.toString();
    }
}
